<?php
/**
 * Created by PhpStorm.
 * User: 93195
 * Date: 2018/6/14
 * Time: 11:06
 */
class PointLogic extends Model
{
    private $userPointModel = null;
    private $pointBillModel = null;
    private $customerId = null;

    public function __construct()
    {
        $this->customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $this->userPointModel = M('module_user_point');
        $this->pointBillModel = M('module_user_point_bill');
        Session::switchCustomer($this->customerId);
    }

    /**增加积分
     * @param $userId /用户id（user表id）
     * @param $num /积分数目
     * @param string $module /积分来源模块
     * @param string $moduleId /模块id（如果是订单就传订单号）
     * @param string $channel /途径
     * @param string $description /描述
     * @param string $pointSchemeId /积分方案id
     * @param string $pointSchemeName /积分方案名称
     * @return bool
     */
    public function addPoint(
        $userId,
        $num,
        $module = '',
        $moduleId = '',
        $channel = '',
        $description = '',
        $pointSchemeId = '',
        $pointSchemeName = ''
    )
    {
        if (!$num) return true;
        $userPoint = $this->userPointModel->where(['userId' => $userId, 'cid' => $this->customerId])->find();
        $isHave = $userPoint;

        (empty($userPoint['pointBalance'])) ? $userPoint['pointBalance'] = 0:'';
        (empty($userPoint['totalPoint'])) ? $userPoint['totalPoint'] = 0:'';
        $newPoint = $userPoint['pointBalance'] + $num;
        $newTotalPoint = $userPoint['totalPoint'] + $num;
        $data = [
            'pointBalance' => $newPoint,
            'totalPoint' => $newTotalPoint,
            'updateTime' => date('Y-m-d H:i:s', time())
        ];
        $this->userPointModel->startTrans();
        if ($isHave) {
            $buyerRes = $this->userPointModel->where(['userId' => $userId, 'cid' => $this->customerId])->save($data);
        } else {
            $data['cid'] = $this->customerId;
            $data['userId'] = $userId;
            $data['totalConsume'] = 0;
            $buyerRes = $this->userPointModel->add($data);
        }
        //生成积分收入记录
        $recordData = [
            'cid' => $this->customerId,
            'userId' => $userId,
            'module' => $module,
            'moduleId' => $moduleId,
            'channel' => $channel,
            'description' => $description,
            'type' => POINT_TYPE_IN,
            'number' => $num,
            'pointSchemeId' => $pointSchemeId,
            'pointSchemeName' => $pointSchemeName,
            'createTime' => date('Y-m-d H:i:s', time())
        ];
        $buyerRecordRes = $this->pointBillModel->add($recordData);

        if (is_numeric($buyerRes) && is_numeric($buyerRecordRes)) {
            $this->userPointModel->commit();
            return $buyerRecordRes;
        } else {
            $this->userPointModel->rollback();
            return false;
        }
    }

    /**扣除积分
     * @param $userId /用户id（user表id）
     * @param $num /积分数目
     * @param string $module /积分来源模块
     * @param string $moduleId /模块id（如果是订单就传订单号）
     * @param string $channel /途径
     * @param string $description /描述
     * @param string $pointSchemeId /积分方案id
     * @param string $pointSchemeName /积分方案名称
     * @param int $out /是否是消费，是的话传1
     * @return bool
     */
    public function deductPoint(
        $userId,
        $num,
        $module = '',
        $moduleId = '',
        $channel = '',
        $description = '',
        $pointSchemeId = '',
        $pointSchemeName = '',
        $out = 0
    )
    {
        if (!$num) return true;
        $userPoint = $this->userPointModel->where(['userId' => $userId, 'cid' => $this->customerId])->find();
        $isHave = $userPoint;

        (empty($userPoint['pointBalance'])) ? $userPoint['pointBalance'] = 0:'';
        (empty($userPoint['totalConsume'])) ? $userPoint['totalConsume'] = 0:'';
        $newPoint = $userPoint['pointBalance'] - $num;
        $newTotalConsumePoint = $userPoint['totalConsume'] + $num;
        $data = [
            'pointBalance' => $newPoint,
            'totalConsume' =>$newTotalConsumePoint,
            'updateTime' => date('Y-m-d H:i:s', time())
        ];
        $this->userPointModel->startTrans();
        if ($isHave) {
            $buyerRes = $this->userPointModel->where(['userId' => $userId, 'cid' => $this->customerId])->save($data);
        } else {
            $data['cid'] = $this->customerId;
            $data['userId'] = $userId;
            $data['totalPoint'] = 0;
            $buyerRes = $this->userPointModel->add($data);
        }
        //生成积分收入记录
        $recordData = [
            'cid' => $this->customerId,
            'userId' => $userId,
            'module' => $module,
            'moduleId' => $moduleId,
            'channel' => $channel,
            'description' => $description,
            'type' => $out ? POINT_TYPE_OUT : POINT_TYPE_DEDUCT,
            'number' => $num,
            'pointSchemeId' => $pointSchemeId,
            'pointSchemeName' => $pointSchemeName,
            'createTime' => date('Y-m-d H:i:s', time())
        ];
        $buyerRecordRes = $this->pointBillModel->add($recordData);

        if (is_numeric($buyerRes) && is_numeric($buyerRecordRes)) {
            $this->userPointModel->commit();
            return true;
        } else {
            $this->userPointModel->rollback();
            return false;
        }
    }

    /**获取用户积分余额
     * @param $userId
     * @return int
     */
    public function getUserPoint($userId)
    {
        $userPoint = $this->userPointModel->where(['userId' => $userId, 'cid' => $this->customerId])->find();
        $point = $userPoint ? $userPoint['pointBalance'] : 0;
        return $point;
    }
}